package com.beiding.workordersystem.common.utils;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ObjectUtils {

    //利用动态代理自动创建一个实体
    public static <F, S extends F> S wrap(F father, S sub) {

        if (father == null || sub == null) {
            throw new IllegalArgumentException("非法参数");
        }

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(sub.getClass());
        enhancer.setCallback(new CallSupper(father));// 设置回调
        return (S) enhancer.create();
    }

    private static class CallSupper implements MethodInterceptor {
        private Object father;
        CallSupper(Object father) {
            this.father = father;
        }
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            Class<?> declaringClass = method.getDeclaringClass();
            if (declaringClass.isInstance(father)) {
                return methodProxy.invoke(father, objects);
            } else {
                return methodProxy.invokeSuper(o, objects);
            }
        }
    }


}
